#include "BlockQueue.hpp"
#include <unistd.h>

//描述生产者 消费者 线程
class thread{
public:
    string name_;
    pthread_t tid_;
    BlockQueue<int>* bq_;
};

//生产者线程执行流
void *Producers(void* arg){
    thread *p= static_cast<thread*>(arg);
    while(true){
        sleep(1);
        int data = rand()%10;
        p->bq_->push(data);
        cout<<p->name_<<" ,生产一个资源,data = " << data << endl;
    }
    return nullptr;
}

//消费者线程执行流
void *Consumers(void* arg){
    thread *c= static_cast<thread*>(arg);
    while(true){
        //sleep(1);
        int data = c->bq_->pop();
        cout<<c->name_<<" ,消费一个资源,data = " << data << endl;
    }
    return nullptr;
}


int main(){ 
    BlockQueue<int> *bq = new BlockQueue<int>(5);
    thread p[3],c[5];//生产者消费者对象
    //创建线程
    for(int i=0;i<3;++i){
        string name = "Producers-";
        name += to_string(i);
        p[i].name_ = name;
        p[i].bq_ = bq;
        pthread_create(&p[i].tid_,nullptr,&Producers,p+i);
    }
    for(int i=0;i<5;++i){
        string name = "Consumers-";
        name += to_string(i);
        c[i].name_ = name;
        c[i].bq_ = bq;
        pthread_create(&c[i].tid_,nullptr,&Consumers,c+i);
    }


    srand(time(nullptr));//随机种子
    while(true);

    //等待线程
    for(int i=0;i<3;++i){
        pthread_join(p[i].tid_,nullptr);
    }
    for(int i=0;i<5;++i){
        pthread_join(c[i].tid_,nullptr);
    }
    delete bq;//释放共享资源
    return 0;
}

